package csu.web.credit_bank.service.impl;

import csu.web.credit_bank.pojo.dto.DailyQuizStatus;
import csu.web.credit_bank.pojo.dto.McqQuestionDto;
import csu.web.credit_bank.pojo.dto.TianxingBaikeResponseDto;
import csu.web.credit_bank.service.CreditRecordsService;
import csu.web.credit_bank.service.CreditSummaryService;
import csu.web.credit_bank.service.QuizService;
import csu.web.credit_bank.utils.Result;
import csu.web.credit_bank.utils.UUIDManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.*;

@Service
public class QuizServiceImpl implements QuizService {

    private static final String TIANXING_API_URL = "https://apis.tianapi.com/baiketiku/index?key={key}";

    @Value("${tianxing.api.key}")
    private String tianxingApiKey;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private UUIDManager uuidManager;
    @Autowired
    private CreditRecordsService creditRecordsService;
    @Autowired
    private CreditSummaryService creditSummaryService;
    private static final int MCQ_CORRECT_ANSWERS_FOR_REWARD = 5;
    private static final int MCQ_CREDITS_REWARD = 10;

    private DailyQuizStatus getOrCreateDailyStatus(String userId) {
        Cache cache = cacheManager.getCache("dailyQuizStatusCache");
        String cacheKey = userId + "_" + LocalDate.now().toString();
        DailyQuizStatus status = cache.get(cacheKey, DailyQuizStatus.class);
        if (status == null) {
            status = new DailyQuizStatus();
            cache.put(cacheKey, status);
        }
        return status;
    }

    @Override
    public Result<McqQuestionDto> getMcqQuestion(String userId) {
        DailyQuizStatus status = getOrCreateDailyStatus(userId);
        if (status.isMcqCreditsAwarded()) {
            return Result.failure("您今日的选择题挑战已完成，请明天再来！");
        }
        try {
            String requestUrl = TIANXING_API_URL.replace("{key}", tianxingApiKey);
            TianxingBaikeResponseDto response = restTemplate.getForObject(requestUrl, TianxingBaikeResponseDto.class);
            if (response == null || response.getCode() != 200 || response.getResult() == null) {
                String errorMessage = (response != null && response.getMsg() != null) ? response.getMsg() : "API无响应或返回错误";
                return Result.failure("获取中文题目失败：" + errorMessage);
            }
            TianxingBaikeResponseDto.QuestionResult apiQuestion = response.getResult();
            List<String> options = new ArrayList<>();
            if (apiQuestion.getAnswerA() != null) options.add(apiQuestion.getAnswerA());
            if (apiQuestion.getAnswerB() != null) options.add(apiQuestion.getAnswerB());
            if (apiQuestion.getAnswerC() != null) options.add(apiQuestion.getAnswerC());
            if (apiQuestion.getAnswerD() != null) options.add(apiQuestion.getAnswerD());
            Collections.shuffle(options);
            McqQuestionDto questionDto = new McqQuestionDto();
            String questionId = uuidManager.getUUID();
            questionDto.setQuestionId(questionId);
            questionDto.setCategory("百科知识");
            questionDto.setDifficulty("随机");
            questionDto.setQuestion(apiQuestion.getTitle());
            questionDto.setOptions(options);
            Cache answerCache = cacheManager.getCache("mcqAnswers");
            if (answerCache != null) {
                String correctAnswerText = "";
                switch (apiQuestion.getAnswer().toUpperCase()) {
                    case "A": correctAnswerText = apiQuestion.getAnswerA(); break;
                    case "B": correctAnswerText = apiQuestion.getAnswerB(); break;
                    case "C": correctAnswerText = apiQuestion.getAnswerC(); break;
                    case "D": correctAnswerText = apiQuestion.getAnswerD(); break;
                }
                answerCache.put(questionId, correctAnswerText);
            }
            return Result.success(questionDto);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("处理中文题目时发生严重错误: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> checkMcqAnswer(String userId, String questionId, String userAnswer) {
        Cache answerCache = cacheManager.getCache("mcqAnswers");
        if (answerCache == null) {
            return Result.failure("服务器错误: 缓存不可用");
        }
        String correctAnswer = answerCache.get(questionId, String.class);
        if (correctAnswer == null) {
            return Result.failure("题目已过期或无效，请换一题");
        }
        if (!correctAnswer.equals(userAnswer)) {
            return Result.failure("回答错误。正确答案是: " + correctAnswer);
        }
        answerCache.evict(questionId);
        DailyQuizStatus status = getOrCreateDailyStatus(userId);
        if (status.isMcqCreditsAwarded()) {
            return Result.failure("您今日的奖励已领取。");
        }
        status.setMcqCorrectCount(status.getMcqCorrectCount() + 1);
        String message = String.format("回答正确！累计正确 %d/5。", status.getMcqCorrectCount());
        if (status.getMcqCorrectCount() >= MCQ_CORRECT_ANSWERS_FOR_REWARD) {
            status.setMcqCreditsAwarded(true);
            try {
                // --- 核心修改：替换占位符为完整代码 ---
                // 1. 创建新的学分记录
//                CreditRecord newRecord = new CreditRecord();
//                newRecord.setId(uuidManager.getUUID());
//                newRecord.setUserId(userId);
//                newRecord.setMethod("选择题挑战");
//                newRecord.setCourseName("累计答对5题");
//                newRecord.setCredits(MCQ_CREDITS_REWARD); // 奖励10学分
//                newRecord.setRecordTime(Date.from(LocalDateTime.now(ZoneId.of("Asia/Shanghai")).atZone(ZoneId.systemDefault()).toInstant()));
//                creditRecordsService.createCreditRecord(newRecord);

                // 2. 更新学分汇总
//                CreditSummary summary = creditSummaryService.getCreditSummaryByUserId(userId);
//                if (summary == null) {
//                    summary = new CreditSummary();
//                    summary.setUserId(userId);
//                    summary.setTotalCredits(MCQ_CREDITS_REWARD);
//                    summary.setLastUpdateTime(new Date());
//                    creditSummaryService.save(summary);
//                } else {
//                    summary.setTotalCredits(summary.getTotalCredits() + MCQ_CREDITS_REWARD);
//                    summary.setLastUpdateTime(new Date());
//                    creditSummaryService.updateCreditSummary(summary);
//                }
                message = String.format("恭喜！累计答对5题，获得10学分！",
                        MCQ_CORRECT_ANSWERS_FOR_REWARD, MCQ_CREDITS_REWARD);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("发放学分失败，事务已回滚。", e);
            }
        }

        String cacheKey = userId + "_" + LocalDate.now().toString();
        cacheManager.getCache("dailyQuizStatusCache").put(cacheKey, status);
        return Result.success(message);
    }
}
